package cn.edu.scut.fsearch.relative;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import jeasy.analysis.MMAnalyzer;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.apache.nutch.util.NutchConfiguration;


public class SuggestedQuery {
	
	private static String basePath = NutchConfiguration.create().get("suggest.dir","./webapps/ROOT/");
	private static String INDEX_DIR = basePath + File.separatorChar + "query-index";
	private static String FIELD_QUERY = "query";
	private static String FIELD_WORD_TIME="word_time";
	
	public static String[] getWordsSuggestion(String prefixword) throws IOException{
		IndexSearcher is = new IndexSearcher(INDEX_DIR);
//		System.out.println(is);
		MMAnalyzer analyzer=new MMAnalyzer();
		String[] querwords=analyzer.segment(prefixword, " ").split(" ");
		PrefixQuery q=new PrefixQuery(new Term(FIELD_QUERY,querwords[0]));
		TopDocs docs = is.search(q,null,11,new Sort(FIELD_WORD_TIME));
		ScoreDoc[] scoreDocs = docs.scoreDocs;
		ArrayList<String> rq = new ArrayList<String>();
		for (int i=0,j=0; i<scoreDocs.length&&j<10; i++) {
			Document doc = is.doc(scoreDocs[i].doc);
			String relative = doc.get(FIELD_QUERY);
			if(relative.startsWith(prefixword)&&!relative.equals(prefixword)){
				//relative+="@about "+doc.get(FIELD_PAGE_NUMBER)+" sites";//word and page-number is split by @
				rq.add(relative);
				j++;
			}
		}
		is.close();
		
		return rq.toArray(new String[rq.size()]);
	}
	
	public static void main(String[] args){
		try{
			String queryString = "华南";
			String[] rq= SuggestedQuery.getWordsSuggestion(queryString);
			for (int i = 0; i < rq.length; i++)
			{
				System.out.println(rq[i]);
			}
			System.out.println("finished");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
